package com.hexacta.hrs.repositories.impl;

import java.util.Calendar;
import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.hexacta.hrs.domain.feedback.Period;
import com.hexacta.hrs.repositories.feedback.PeriodObjectRepository;

public class PeriodRecordObjectRepository extends
		HibernateRecordObjectRepository<Period> implements PeriodObjectRepository {

	public PeriodRecordObjectRepository(Class<Period> entityClass) {
		super(entityClass);
	}

	@Override
	public Collection<Period> findAll() {
		Criteria criteria = this.getSession().createCriteria(Period.class);
		return criteria.list();
	}

	@Override
	public Period getOpenPeriod() {
		Criteria criteria = this.getSession().createCriteria(Period.class,"period");
		
		criteria.add(Restrictions.eq("closed", false));
		
		return (Period) criteria.uniqueResult();
	}
	
	public void closePeriod(Period period){
		period.setClosed(true);
		period.setCloseDay(Calendar.getInstance());
		
		this.save(period);
	}
	
	public void closePeriod(String year){
		Period period = getPeriodByYear(year);
		
		period.setClosed(true);
		period.setCloseDay(Calendar.getInstance());
		
		this.save(period);
	}
	
	public void openPeriod(Period period){
		period.setClosed(false);
		period.setCloseDay(null);
		
		this.save(period);
	}
	
	public void openPeriod(String year){
		Period period = getPeriodByYear(year);
		
		period.setClosed(false);
		period.setCloseDay(null);
		
		this.save(period);
	}

	@Override
	public Period getLastPeriod() {
		Criteria criteria = this.getSession().createCriteria(Period.class,"period");
		
		criteria.setProjection(Projections.max("year"));
		String year = (String) criteria.uniqueResult();
		
		return getPeriodByYear(year);
	}

	public Period getPeriodByYear(String year){
		Criteria criteria = this.getSession().createCriteria(Period.class,"period");
		
		criteria.add(Restrictions.eq("year", year));
		
		return (Period) criteria.uniqueResult();
	}
}
